﻿using Bricks.Business.Data.Repositories.ScheduleManagement;
using Bricks.Business.Models.ScheduleManagement;
using Bricks.Site.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using Bricks.Component.Utils;

namespace Bricks.Business.Service.Impl
{
    [Export(typeof(IBridgeStatisticsService))]
    /// <summary>
    /// 桥梁统计服务实现
    /// </summary>
    public class BridgeStatisticsService : IBridgeStatisticsService
    {
        [Import]
        protected IBridgeStatisticsRepository BridgeStatisticsRepository { get; set; }

        [Import]
        protected IBridgeStatisticsDetailRepository BridgeStatisticsDetailRepository { get; set; }

        public IQueryable<BridgeStatistics> BridgeStatisticses
        {
            get { return BridgeStatisticsRepository.Entities; }
        }

        public IQueryable<BridgeStatisticsDetail> BridgeStatisticsDetails
        {
            get { return BridgeStatisticsDetailRepository.Entities; }
        }

        /// <summary>
        /// 获取桥梁统计列表
        /// </summary>
        /// <param name="projectID"></param>
        /// <param name="contractID"></param>
        /// <returns></returns>
        public List<BridgeStatisticsView> GetBridgeTotalList(Guid projectID, Guid contractID)
        {
            List<BridgeStatisticsView> result = new List<BridgeStatisticsView>();
            var dataList = BridgeStatisticses.Where(m => m.ProjectID == projectID && m.ContractID == contractID).OrderByDescending(m => m.AddDate);
            if (dataList != null && dataList.Count() > 0)
            {
                BridgeStatisticsView record;
                foreach (BridgeStatistics bs in dataList)
                {
                    record = new BridgeStatisticsView();
                    record.ID = bs.ID;
                    record.ProjectID = bs.ProjectID;
                    record.ContractID = bs.ContractID;
                    record.StatisticalCycle = bs.StatisticalCycle;

                    //明细过滤
                    var bridgeStatisticsDetails = from m in BridgeStatisticsDetails
                                                  where m.BridgeStatisticsID == bs.ID
                                                  select m;

                    if (bridgeStatisticsDetails != null && bridgeStatisticsDetails.Count() > 0)
                    {
                        //汇总各个字段
                        record.BasicDesignTotal = bridgeStatisticsDetails.Sum(m => m.BasicDesign);
                        record.BasicRealityTotal = bridgeStatisticsDetails.Sum(m => m.BasicReality);
                        record.BottomBuildDesignTotal = bridgeStatisticsDetails.Sum(m => m.BottomBuildDesign);
                        record.BottomBuildRealityTotal = bridgeStatisticsDetails.Sum(m => m.BottomBuildReality);
                        record.PrecutInstallDesignTotal = bridgeStatisticsDetails.Sum(m => m.PrecutInstallDesign);
                        record.PrecutInstallRealityTotal = bridgeStatisticsDetails.Sum(m => m.PrecutInstallReality);
                        record.TopBuildDesignTotal = bridgeStatisticsDetails.Sum(m => m.TopBuildDesign);
                        record.TopBuildRealityTotal = bridgeStatisticsDetails.Sum(m => m.TopBuildReality);
                        record.BridgeSurfaceDesignTotal = bridgeStatisticsDetails.Sum(m => m.BridgeSurfaceDesign);
                        record.BridgeSurfaceRealityTotal = bridgeStatisticsDetails.Sum(m => m.BridgeSurfaceReality);

                        //因为可能为空，所以需要进行空判断后再计算
                        //实际
                        var brt = record.BasicRealityTotal.HasValue ? record.BasicRealityTotal : 0;
                        var bbrt = record.BottomBuildRealityTotal.HasValue ? record.BottomBuildRealityTotal : 0;
                        var pirt = record.PrecutInstallRealityTotal.HasValue ? record.PrecutInstallRealityTotal : 0;
                        var tbrt = record.TopBuildRealityTotal.HasValue ? record.TopBuildRealityTotal : 0;
                        var bsrt = record.BridgeSurfaceRealityTotal.HasValue ? record.BridgeSurfaceRealityTotal : 0;

                        //设计
                        var bdt = record.BasicDesignTotal.HasValue ? record.BasicDesignTotal : 0;
                        var bbdt = record.BottomBuildDesignTotal.HasValue ? record.BottomBuildDesignTotal : 0;
                        var pidt = record.PrecutInstallDesignTotal.HasValue ? record.PrecutInstallDesignTotal : 0;
                        var tbdt = record.TopBuildDesignTotal.HasValue ? record.TopBuildDesignTotal : 0;
                        var bsdt = record.BridgeSurfaceDesignTotal.HasValue ? record.BridgeSurfaceDesignTotal : 0;

                        //总完成进度
                        decimal? countResult = 0;
                        var designTotal = bdt + bbdt + pidt + tbdt + bsdt;
                        if (designTotal.HasValue && designTotal.Value != 0)
                            countResult = ((brt + bbrt + pirt + tbrt + bsrt) / (designTotal.Value));
                        if (countResult != null && countResult.HasValue)
                            record.TotalFinishedProgress = (countResult.Value * 100).ToString("F2") + "%";
                        else
                            record.TotalFinishedProgress = "0%";
                    }
                    result.Add(record);
                }
            }
            return result;
        }

        /// <summary>
        /// 获取桥梁统计明细列表
        /// </summary>
        /// <param name="bridgeID">桥梁ID</param>
        /// <param name="newBridgeID">新的桥梁ID（拷贝上月数据时使用）</param>
        /// <returns></returns>
        public List<BridgeStatisticsDetailView> GetBridgeDetailList(Guid bridgeID, Guid newBridgeID)
        {
            List<BridgeStatisticsDetailView> result = new List<BridgeStatisticsDetailView>();
            var dataList = BridgeStatisticsDetails.Where(m => m.BridgeStatisticsID == bridgeID);
            if (dataList != null && dataList.Count() > 0)
            {
                BridgeStatisticsDetailView record;
                foreach (BridgeStatisticsDetail detail in dataList)
                {
                    record = new BridgeStatisticsDetailView();
                    record = detail.CopyTo<BridgeStatisticsDetailView>();
                    if (!newBridgeID.Equals(Guid.Empty))
                        record.BridgeStatisticsID = newBridgeID;

                    //因为可能为空，所以需要进行空判断后再计算
                    //实际
                    var br = detail.BasicReality.HasValue ? detail.BasicReality : 0;
                    var bbr = detail.BottomBuildReality.HasValue ? detail.BottomBuildReality : 0;
                    var pir = detail.PrecutInstallReality.HasValue ? detail.PrecutInstallReality : 0;
                    var tbr = detail.TopBuildReality.HasValue ? detail.TopBuildReality : 0;
                    var bsr = detail.BridgeSurfaceReality.HasValue ? detail.BridgeSurfaceReality : 0;

                    //设计
                    var bd = detail.BasicDesign.HasValue ? detail.BasicDesign : 0;
                    var bbd = detail.BottomBuildDesign.HasValue ? detail.BottomBuildDesign : 0;
                    var pid = detail.PrecutInstallDesign.HasValue ? detail.PrecutInstallDesign : 0;
                    var tbd = detail.TopBuildDesign.HasValue ? detail.TopBuildDesign : 0;
                    var bsd = detail.BridgeSurfaceDesign.HasValue ? detail.BridgeSurfaceDesign : 0;

                    decimal? countResult = 0;
                    var designTotal = bd + bbd + pid + tbd + bsd;
                    if (designTotal.HasValue && designTotal.Value != 0)
                        countResult = ((br + bbr + pir + tbr + bsr) / (designTotal.Value));
                    if (countResult != null && countResult.HasValue)
                        record.TotalFinishedProgress = (countResult.Value * 100).ToString("F2") + "%";
                    else
                        record.TotalFinishedProgress = "0%";

                    result.Add(record);
                }
            }
            return result;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="view"></param>
        /// <param name="details"></param>
        /// <returns></returns>
        public OperationResult Add(BridgeStatisticsView view)
        {
            var result = new OperationResult(OperationResultType.NoChanged);
            BridgeStatistics bs = new BridgeStatistics();
            bs = view.CopyTo<BridgeStatistics>();
            //保存桥梁
            if (BridgeStatisticsRepository.Insert(bs) > 0)
            {
                //保存桥梁明细
                string detailListJson = view.BridgeDetailListJson;
                if (!String.IsNullOrEmpty(detailListJson))
                {
                    List<BridgeStatisticsDetailView> detailViewList = JsonHelper.JsonDeserialize<List<BridgeStatisticsDetailView>>(detailListJson);
                    if (detailViewList != null && detailViewList.Count > 0)
                    {
                        List<BridgeStatisticsDetail> detailList = new List<BridgeStatisticsDetail>();
                        BridgeStatisticsDetail detail;
                        foreach (BridgeStatisticsDetailView item in detailViewList)
                        {
                            detail = new BridgeStatisticsDetail();
                            detail = item.CopyTo<BridgeStatisticsDetail>();
                            detail.ID = GuidHelper.NewGuid();
                            detailList.Add(detail);
                        }
                        if (detailList.Count > 0)
                        {
                            if (BridgeStatisticsDetailRepository.Insert(detailList) > 0)
                            {
                                result = new OperationResult(OperationResultType.Success, "保存记录和明细成功");
                            }
                        }
                    }
                }
                result = new OperationResult(OperationResultType.Success, "保存记录成功");
            }
            return result;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="view"></param>
        /// <param name="details"></param>
        /// <returns></returns>
        public OperationResult Modify(BridgeStatisticsView view)
        {
            var result = new OperationResult(OperationResultType.NoChanged);
            BridgeStatistics bs = new BridgeStatistics();
            bs = view.CopyTo<BridgeStatistics>();
            //保存桥梁
            if (BridgeStatisticsRepository.Update(bs) >= 0)
            {
                //删除旧的桥梁明细
                var oldDetailList = BridgeStatisticsDetails.Where(m => m.BridgeStatisticsID == bs.ID);
                if (oldDetailList != null && oldDetailList.Count() > 0)
                {
                    BridgeStatisticsDetailRepository.Delete(oldDetailList);
                }

                //保存桥梁明细
                string detailListJson = view.BridgeDetailListJson;
                if (!String.IsNullOrEmpty(detailListJson))
                {
                    //json->对象（注：使用此方法，当为空时，可能转换出错）
                    List<BridgeStatisticsDetailView> detailViewList = JsonHelper.JsonDeserialize<List<BridgeStatisticsDetailView>>(detailListJson);
                    if (detailViewList != null && detailViewList.Count > 0)
                    {
                        List<BridgeStatisticsDetail> detailList = new List<BridgeStatisticsDetail>();
                        BridgeStatisticsDetail detail;
                        foreach (BridgeStatisticsDetailView item in detailViewList)
                        {
                            detail = new BridgeStatisticsDetail();
                            detail = item.CopyTo<BridgeStatisticsDetail>();
                            detailList.Add(detail);
                        }
                        if (detailList.Count > 0)
                        {
                            if (BridgeStatisticsDetailRepository.Insert(detailList) > 0)
                            {
                                result = new OperationResult(OperationResultType.Success, "保存记录和明细成功");
                            }
                        }
                    }
                }
                result = new OperationResult(OperationResultType.Success, "保存记录和明细成功");
            }
            return result;
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="bridgeStatisticsView"></param>
        /// <param name="saveList"></param>
        /// <param name="isUpdateDetails"></param>
        public void Save(BridgeStatisticsView bridgeStatisticsView, List<BridgeStatisticsDetailView> saveList, bool isUpdateDetails = true)
        {
            BridgeStatistics record = BridgeStatisticsRepository.Entities.FirstOrDefault(a => a.ID == bridgeStatisticsView.ID);
            if (record != null)
            {
                Modify(bridgeStatisticsView);
            }
            else
            {
                Add(bridgeStatisticsView);
            }

            if (isUpdateDetails)
            {
                DeleteBridgeStatisticsDetails(bridgeStatisticsView.ID);
                foreach (BridgeStatisticsDetailView bsd in saveList)
                {
                    InsertBridgeStatisticsDetail(bsd);
                }
            }
        }

        /// <summary>
        /// 清空桥梁对应的明细记录
        /// </summary>
        /// <param name="bridgeStatisticsID"></param>
        private void DeleteBridgeStatisticsDetails(Guid bridgeStatisticsID)
        {
            List<BridgeStatisticsDetail> lstBridgeStatisticsDetails = BridgeStatisticsDetailRepository.Entities.Where(a => a.BridgeStatisticsID == bridgeStatisticsID).ToList();
            foreach (BridgeStatisticsDetail bsd in lstBridgeStatisticsDetails)
            {
                BridgeStatisticsDetailRepository.Delete(bsd.ID);
            }
        }

        /// <summary>
        /// 插入桥梁明细记录
        /// </summary>
        /// <param name="bridgeStatisticsDetailView"></param>
        private void InsertBridgeStatisticsDetail(BridgeStatisticsDetailView bridgeStatisticsDetailView)
        {
            BridgeStatisticsDetail record = new BridgeStatisticsDetail();
            record = bridgeStatisticsDetailView.CopyTo<BridgeStatisticsDetail>();
            BridgeStatisticsDetailRepository.Insert(record);
        }

        /// <summary>
        /// 获取桥梁信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public BridgeStatisticsView GetBridge(Guid id)
        {
            BridgeStatisticsView result = new BridgeStatisticsView();
            var bridge = BridgeStatisticses.FirstOrDefault(m => m.ID == id);
            if (bridge != null)
            {
                result = bridge.CopyTo<BridgeStatisticsView>();
            }
            return result;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public OperationResult Delete(Guid id)
        {
            var result = new OperationResult(OperationResultType.NoChanged);
            if (id != null && !id.Equals(Guid.Empty))
            {
                try
                {
                    //查找子记录并删除
                    var detailList = BridgeStatisticsDetails.Where(m => m.BridgeStatisticsID == id);
                    if (detailList != null && detailList.Count() > 0)
                    {
                        BridgeStatisticsDetailRepository.Delete(detailList);
                    }

                    //查找主记录并删除
                    var bridge = BridgeStatisticses.FirstOrDefault(m => m.ID == id);
                    if (bridge != null)
                    {
                        if (BridgeStatisticsRepository.Delete(bridge) > 0)
                        {
                            result = new OperationResult(OperationResultType.Success, "删除成功");
                        }
                    }
                }
                catch (Exception ex)
                {
                    result = new OperationResult(OperationResultType.Error, ex.Message);
                }
            }
            return result;
        }
    }
}
